package org.ghost.spring.cloud.config.client.demo.component.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public class SpringUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (SpringUtil.applicationContext == null) {
            SpringUtil.applicationContext = applicationContext;
        }
    }

    private static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String name) {
        if (getApplicationContext() != null) {
            return getApplicationContext().getBean(name);
        }
        return null;
    }

    public static <T> T getBean(Class<T> clazz) {
        if (getApplicationContext() != null) {
            return getApplicationContext().getBean(clazz);
        }
        return null;
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        if (getApplicationContext() != null) {
            return getApplicationContext().getBean(name, clazz);
        }
        return null;
    }

    public static Environment getEnvironment() {
        if (getApplicationContext() != null) {
            return getApplicationContext().getEnvironment();
        }
        return null;
    }
}
